from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List, Optional
from app.models.passenger import Passenger
from app.schemas.passenger import PassengerCreate, PassengerUpdate

class PassengerService:
    def __init__(self, db: Session):
        self.db = db

    def create_passenger(self, passenger: PassengerCreate) -> Passenger:
        """创建新乘客"""
        db_passenger = Passenger(**passenger.dict())
        self.db.add(db_passenger)
        self.db.commit()
        self.db.refresh(db_passenger)
        return db_passenger

    def get_passenger(self, passenger_id: int) -> Optional[Passenger]:
        """根据ID获取乘客信息"""
        return self.db.query(Passenger).filter(Passenger.id == passenger_id).first()

    def get_passenger_by_email(self, email: str) -> Optional[Passenger]:
        """根据邮箱获取乘客信息"""
        return self.db.query(Passenger).filter(Passenger.email == email).first()

    def get_passenger_by_passport(self, passport_number: str) -> Optional[Passenger]:
        """根据护照号获取乘客信息"""
        return self.db.query(Passenger).filter(Passenger.passport_number == passport_number).first()

    def get_passengers(self, skip: int = 0, limit: int = 100) -> List[Passenger]:
        """获取乘客列表"""
        return self.db.query(Passenger).offset(skip).limit(limit).all()

    def search_passengers(self, query: str) -> List[Passenger]:
        """搜索乘客（根据姓名、邮箱、护照号或手机号）"""
        return self.db.query(Passenger).filter(
            or_(
                Passenger.first_name.ilike(f"%{query}%"),
                Passenger.last_name.ilike(f"%{query}%"),
                Passenger.email.ilike(f"%{query}%"),
                Passenger.passport_number.ilike(f"%{query}%"),
                Passenger.phone.ilike(f"%{query}%")
            )
        ).all()

    def update_passenger(self, passenger_id: int, passenger_update: PassengerUpdate) -> Optional[Passenger]:
        """更新乘客信息"""
        db_passenger = self.get_passenger(passenger_id)
        if not db_passenger:
            return None

        update_data = passenger_update.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_passenger, field, value)

        self.db.commit()
        self.db.refresh(db_passenger)
        return db_passenger

    def delete_passenger(self, passenger_id: int) -> bool:
        """删除乘客"""
        db_passenger = self.get_passenger(passenger_id)
        if not db_passenger:
            return False

        self.db.delete(db_passenger)
        self.db.commit()
        return True